package net.admin.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminFrontController extends HttpServlet{
	
	private Map commandMap = new HashMap();
	
	@Override
	public void init(ServletConfig config) throws ServletException{
		String props = config.getInitParameter("adminConfig");
		Properties pr = new Properties();
		FileInputStream f = null;
		
		System.out.println("net.admin.action.AdminFrontController.init()   props="+props);
		
		try{
			f = new FileInputStream(props);
			pr.load(f);
		}catch(IOException e){
			throw new ServletException(e);
		}finally{
			if(f!=null){try{f.close();}catch(IOException e){}}
		}
		
		Iterator keyIter = pr.keySet().iterator();
		
		while(keyIter.hasNext()){
			String command = (String)keyIter.next();
			String className = pr.getProperty(command);
			System.out.println("className : "+className);
			try{
				Class commandClass = Class.forName(className);
				Object commandInstance = commandClass.newInstance();
				commandMap.put(command, commandInstance);
			}catch(ClassNotFoundException e){
				throw new ServletException(e);
			} catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
		}
	}
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		this.processRequest(request, response);
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		this.processRequest(request, response);
	}
	
	public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		System.out.println("AdminFrontController.processRequest()");
		Action action=null;
	    ActionForward forward=null;
		try {
			String command = request.getRequestURI();
	        if (command.indexOf(request.getContextPath()) == 0) {
	        	command = command.substring(request.getContextPath().length());
	        	System.out.println("command="+command);
	        }
	        action = (Action)commandMap.get(command);  
	        forward = action.execute(request, response);
		} catch(Throwable e) {
			throw new ServletException(e);
		}
			
		if(forward.isRedirect()){
			response.sendRedirect(forward.getPath());
		}else{
			RequestDispatcher dispatcher =request.getRequestDispatcher(forward.getPath());
			dispatcher.forward(request, response);
		}
	}
}
